package com.jiangjiang.eshop.cart.biz;

import com.jiangjiang.eshop.cart.domain.ShoppingCartEntity;
import com.jiangjiang.eshop.cart.domain.ShoppingCartItemEntity;
import com.jiangjiang.eshop.cart.dto.ShoppingCartDTO;
import com.jiangjiang.eshop.cart.dto.ShoppingCartItemDTO;
import com.jiangjiang.eshop.cart.service.ShoppingCartItemService;
import com.jiangjiang.eshop.cart.service.ShoppingCartService;
import com.jiangjiang.eshop.commodity.dto.GoodsSkuDTO;
import com.jiangjiang.eshop.commodity.service.CommodityService;
import com.jiangjiang.eshop.common.help.DateHelper;
import com.jiangjiang.eshop.inventory.service.InventoryService;
import com.jiangjiang.eshop.promotion.dto.PromotionActivityDTO;
import com.jiangjiang.eshop.promotion.service.PromotionFacadeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @ClassName ShoppingCartBiz
 * @Description 购物车业务处理类
 * @Author jhw
 * @Date 2021/6/1 22:43
 * @Version 1.0
 **/
@Slf4j
@Component
public class ShoppingCartBiz {
    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private ShoppingCartItemService shoppingCartItemService;

    @Autowired
    private DateHelper dateHelper;

    @Autowired
    private CommodityService commodityService;
    @Autowired
    private InventoryService inventoryService;
    @Autowired
    private PromotionFacadeService promotionFacadeService;



    /**
     * 将商品加入到购物车
     * @param userAccountId 用户账户id
     * @param goodsSkuId 商品sku id
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean addShoppingCartItem(Long userAccountId,Long goodsSkuId) throws ParseException {
        Date currentDate = dateHelper.getCurrentDate();
        // 1.查询这个用户有没有购物车,如果没有购物车新增一条购物车数据
        ShoppingCartEntity shoppingCart = shoppingCartService.getShoppingCartByUserAccountId(userAccountId);
        if(Objects.isNull(shoppingCart)){
            shoppingCart = new ShoppingCartEntity();
            shoppingCart.setUserAccountId(userAccountId);
            shoppingCart.setGmtCreate(currentDate);
            shoppingCart.setGmtModified(currentDate);
            shoppingCartService.save(shoppingCart);
        }

        // 查询改商品之前有没有添加过购物车，如果没有则新增一条购物条目记录，如果之前添加过则数量叠加后更新该购物车条目

        ShoppingCartItemEntity item = shoppingCartItemService
                .getShoppingCartItemByGoodsSkuId(shoppingCart.getId(), goodsSkuId);

        if(Objects.isNull(item)){
            item = new ShoppingCartItemEntity();
            item.setShoppingCartId(shoppingCart.getId());
            item.setGoodsSkuId(goodsSkuId);
            item.setPurchaseQuantity(1L);
            item.setGmtCreate(currentDate);
            item.setGmtModified(currentDate);
            shoppingCartItemService.save(item);
        } else {
            item.setPurchaseQuantity(item.getPurchaseQuantity() + 1L);
            item.setGmtModified(currentDate);
            shoppingCartItemService.updateById(item);
        }
        return Boolean.TRUE;
    }

    /**
     * 查看购物车
     *
     * @param userAccountId 用户账户
     * @return 查询结果
     */
    public ShoppingCartDTO viewShoppingCart(Long userAccountId) {
        // 查询购物车数据
        ShoppingCartDTO dto = new ShoppingCartDTO();
        ShoppingCartEntity entity = shoppingCartService.getShoppingCartByUserAccountId(userAccountId);
        if(Objects.isNull(entity)){
            return dto;
        }

        dto.setGmtCreate(entity.getGmtCreate());
        dto.setGmtModified(entity.getGmtModified());
        dto.setId(entity.getId());
        dto.setUserAccountId(entity.getUserAccountId());
        dto.setShoppingCartItemDTOList(convertItemDTOList(entity.getId()));

        return dto;
    }

    /**
     * 组装购物车条目数据
     * @param shoppingCartId
     * @return
     */
    private List<ShoppingCartItemDTO> convertItemDTOList(Long shoppingCartId) {

        return shoppingCartItemService.getShoppingCartItemByCartId(shoppingCartId).stream().map(item -> {
            ShoppingCartItemDTO itemDTO = ShoppingCartItemDTO.builder()
                    .id(item.getId())
                    .purchaseQuantity(item.getPurchaseQuantity())
                    .goodsSkuId(item.getGoodsSkuId())
                    .gmtModified(item.getGmtModified())
                    .gmtCreate(item.getGmtCreate())
                    .build();

             // 补充其他属性
            setGoodsRelatedData(itemDTO);
            setStockRelatedData(itemDTO);
            setPromotionRelatedData(itemDTO);
            return itemDTO;

        }).collect(Collectors.toList());
    }

    /**
     * 给购物车条目设置商品相关的数据
     * @param itemDTO 购物车条目
     */
    private void setGoodsRelatedData(ShoppingCartItemDTO itemDTO) {
        GoodsSkuDTO goodsSkuDTO = commodityService.getGoodsSkuById(
                itemDTO.getGoodsSkuId());

        itemDTO.setGoodsId(goodsSkuDTO.getGoodsId());
        itemDTO.setGoodsHeight(goodsSkuDTO.getGoodsHeight());
        itemDTO.setGoodsLength(goodsSkuDTO.getGoodsLength());
        itemDTO.setGoodsName(goodsSkuDTO.getGoodsName());
        itemDTO.setGoodsSkuCode(goodsSkuDTO.getGoodsSkuCode());
        itemDTO.setGoodsWidth(goodsSkuDTO.getGoodsWidth());
        itemDTO.setGrossWeight(goodsSkuDTO.getGrossWeight());
        itemDTO.setSalePrice(goodsSkuDTO.getSalePrice());
        itemDTO.setSaleProperties(goodsSkuDTO.getSaleProperties());
    }

    /**
     * 给购物车条目设置库存相关的数据
     * @param itemDTO 购物车条目
     */
    private void setStockRelatedData(ShoppingCartItemDTO itemDTO) {
        Long saleStockQuantity = inventoryService.getSaleStockQuantity(
                itemDTO.getGoodsSkuId());
        itemDTO.setSaleStockQuantity(saleStockQuantity);
    }

    /**
     * 给购物车条目设置促销相关的数据
     * @param itemDTO 购物车条目
     */
    private void setPromotionRelatedData(ShoppingCartItemDTO itemDTO) {
        List<PromotionActivityDTO> promotionActivityDTOs = promotionFacadeService
                .listByGoodsId(itemDTO.getGoodsId());
        if(CollectionUtils.isEmpty(promotionActivityDTOs)) {
            return;
        }
        itemDTO.setPromotionActivityDTOList(promotionActivityDTOs);
    }

}
